<?php

namespace app\home\controller;

// 引入公共控制器
use app\common\controller\Home;

class Subject  extends Home
{
  protected $noNeedLogin = ['search', 'info'];


  public function _initialize()
  {
    parent::_initialize();
    // 如果用助手调用多级模型 例如：路径：app\common\model\Business\Business
    $this->BusinessModel = model('Business.Business');
    $this->SubjectModel = model('Subject.Subject');
    $this->ChapterModel = model('Subject.Chapter');
    $this->OrderModel = model('Subject.Order');
    $this->RecordModel = model('Business.Record');
    $this->CommentModel = model('Subject.Comment'); //评论模型
  }

  // 搜索页
  public function search()
  {
    if ($this->request->isAjax()) {
      $page = $this->request->param('page', 1, 'trim');
      $limit = $this->request->param('limit', 10, 'trim');
      $keywords = $this->request->param('keywords', '', 'trim');

      // 获取总数
      $count = $this->SubjectModel->where('title', 'like', "%$keywords%")->count();

      // 获取分页数据
      $list = $this->SubjectModel->where('title', 'like', "%$keywords%")->order('createtime', 'DESC')->page($page, $limit)->select();

      $data = [
        'count' => $count,
        'list' => $list
      ];

      if ($list) {
        $this->success('', '', $data);
      } else {
        $this->error();
      }
    }
    $this->assign([
      'status' => 'search'
    ]);
    return $this->view->fetch();
  }

  // 详情页
  public function info()
  {
    $subid = $this->request->param('subid', 0, 'trim');
    $info = $this->SubjectModel->find($subid);
    $likes_status = false;
    $LoginUser = cookie('LoginUser') ?? '';

    if ($LoginUser) {
      // 判断是否已点赞
      $likelist = !empty($info['likes']) ? explode(',', $info['likes']) : [];

      if (in_array($LoginUser['id'], $likelist)) {
        $likes_status = true;
      }
    }
    $info['likes_status'] = $likes_status;

    $chapterlist = $this->ChapterModel->where('subid', $subid)->select();

    //评论列表
    $commentlist = $this->CommentModel
      ->alias('c')
      ->join('pre_business b', "c.busid = b.id and c.subid = $subid")
      ->order('b.createtime', 'DESC')
      ->select();
      
     /*  $commentlist->select();
      halt($commentlist->getLastSql()); */

    $this->assign([
      'subid' => $subid,
      'info' => $info,
      'chapterlist' => $chapterlist,
      'commentlist' => $commentlist,
      'commentlistcount' => count($commentlist)
    ]);
    return $this->view->fetch();
  }

  // 评论列表页
/*    public function commentlist()
  {
    $subid = $this->request->param('subid', 0, 'trim');
  
    //评论列表
    $commentlist = $this->CommentModel
      ->alias('c')
      ->join('pre_business b', "c.busid = b.id and c.subid = $subid")
      ->order('b.createtime', 'DESC')
      ->select();

    // halt($commentlist);
    $this->assign([
      'commentlist' => $commentlist
    ]);
    return $this->view->fetch();
  } 
*/

  // 评论列表页
  public function commentlist()
  {
    if ($this->request->isAjax()) {
      
      $subid = $this->request->param('subid', 0, 'trim');
      $page = $this->request->param('page', 1, 'trim');
      $limit = $this->request->param('limit', 10, 'trim');

      // 获取总数
      $count = $this->CommentModel
        ->alias('c')
        ->join('pre_business b', "c.busid = b.id and c.subid = $subid")
        ->order('b.createtime', 'DESC')
        ->count();

      // 获取分页数据
      //评论列表
      $list = $this->CommentModel
        ->alias('c')
        ->join('pre_business b', "c.busid = b.id and c.subid = $subid")
        ->order('b.createtime', 'DESC')
        ->page($page, $limit)
        ->select();

        $data = [
          'count' => $count,
          'list' => $list
        ];

      if ($list) {
        $this->success('', '', $data);
      } else {
        $this->error();
      }
    }
    return $this->view->fetch();
  }

  // 点赞
  public function like()
  {
    $subid = $this->request->param('subid', 0, 'trim');

    $info = $this->SubjectModel->find($subid);

    if (!$info) {
      $this->error('课程不存在');
    }

    $likelist = !empty($info['likes']) ? explode(',', $info['likes']) : [];

    // 已点赞
    if (in_array($this->LoginUser['id'], $likelist)) {
      // 获取下标
      $key = array_search($this->LoginUser['id'], $likelist);

      // 删除元素
      unset($likelist[$key]);

      $data = [
        'id' => $subid,
        'likes' => implode(',', $likelist)
      ];

      $result = $this->SubjectModel->isUpdate()->save($data);

      if (!$result) {
        $this->error('取消点赞失败');
      }

      $this->success('取消点赞成功');
    }
    // 未点赞
    else {
      $likelist[] = $this->LoginUser['id'];
      $data = [
        'id' => $subid,
        'likes' => implode(',', $likelist)
      ];

      $result = $this->SubjectModel->isUpdate()->save($data);

      if (!$result) {
        $this->error('点赞失败');
      }

      $this->success('点赞成功');
    }
  }

  // 播放
  public function play()
  {
    $subid = $this->request->param('subid', 0, 'trim');
    $chapterid = $this->request->param('chapterid', 0, 'trim');

    $info = $this->SubjectModel->find($subid);

    if (!$info) {
      $this->error('课程不存在');
    }

    $orderinfo = $this->OrderModel->where(['subid' => $subid, 'busid' => $this->LoginUser['id']])->find();

    if (!$orderinfo) {
      $this->error('未购买，请先购买该课程', '', ['buy' => true]);
    }

    $where = [];

    $where['subid'] = $subid;

    if ($chapterid > 0) {
      $where['id'] = $chapterid;
    }

    $chpaterinfo = $this->ChapterModel->where($where)->find();

    if (!$chpaterinfo) {
      $this->error('暂无章节数据');
    }

    $this->success('', '', $chpaterinfo);
  }



  // 购买
  public function buy()
  {
    $subid = $this->request->param('subid', 0, 'trim');

    $info = $this->SubjectModel->find($subid);

    if (!$info) {
      $this->error('课程不存在');
    }

    // bcsub — 两个任意精度数字的减法
    $money = bcsub($this->LoginUser['money'], $info['price'], 2);

    if ($money < 0) {
      $this->error('余额不足，请去充值');
    }

    /*
            1、pre_subject_order 订单表 新增
            2、pre_business      用户表 更新
            3、pre_business_record  消费记录表 新增
        */

    $this->BusinessModel->startTrans();
    $this->OrderModel->startTrans();
    $this->RecordModel->startTrans();

    $OrderData = [
      'subid' => $subid,
      'busid' => $this->LoginUser['id'],
      'total' => $info['price'],
      'code' => build_code('TP')
    ];

    // 订单表新增
    $OrderStatus = $this->OrderModel->save($OrderData);

    if ($OrderStatus === false) {
      $this->error($this->OrderModel->getError());
    }

    $BusinessData = [
      'id' => $this->LoginUser['id'],
      'money' => $money
    ];

    // 用户表更新
    $BusinessStatus = $this->BusinessModel->isUpdate()->save($BusinessData);

    if ($BusinessStatus === false) {
      // 回滚事务
      $this->OrderModel->rollback();
      $this->error($this->BusinessModel->getError());
    }

    $RecordData = [
      'total' => $info['price'],
      'content' => '购买课程：【' . $info['title'] . '】花费了 ￥' . $info['price'] . ' 元',
      'busid' => $this->LoginUser['id'],
      'state' => '1'
    ];

    $RecordStatus = $this->RecordModel->save($RecordData);

    if ($RecordStatus === false) {
      $this->OrderModel->rollback();
      $this->BusinessModel->rollback();
      $this->error($this->RecordModel->getError());
    }

    if ($BusinessStatus === false || $OrderStatus === false || $RecordStatus === false) {
      $this->OrderModel->rollback();
      $this->BusinessModel->rollback();
      $this->RecordModel->rollback();
      $this->error('购买失败');
    } else {
      // 提交事务
      $this->OrderModel->commit();
      $this->BusinessModel->commit();
      $this->RecordModel->commit();
      $this->success('购买成功');
    }
  }
}
